#include "stdTcpServer.h"
#include <iostream>
#include <json-c/json.h>
#include "stdShared.h"

using namespace std;

#define SERVER_PORT 8888
#define SIZE 20
#define BUFFERSIZE 128

/* 首页面 */
void signUpLoginInterFace()
{

    cout << "1.注册" << endl;
    cout << "2.登录" << endl;
}

/* 注册函数 */
int registerInfo(StdTcpSocket *client)
{
    string username;
    cout << "请输入账号:";
    cin >> username;

    string password;
    cout << "请输入密码:";
    cin >> password;

    /* 信息打包为json发送 */
    /* 1.创建json对象 */
    json_object *jsonObj = json_object_new_object();

    /* 2.向json对象添加<key,value>键值对 */
    json_object_object_add(jsonObj, "type", json_object_new_int(REGISTER));
    json_object_object_add(jsonObj, "name", json_object_new_string(username.c_str()));
    json_object_object_add(jsonObj, "passwd", json_object_new_string(password.c_str()));

    /* 3.将json对象转化为字符串 */
    const char *jsonStr = json_object_to_json_string(jsonObj);
    cout << "jsonStr" << jsonStr << endl;

    /* 4.发送到服务器 */
    client->sendMessage(jsonStr);

    /* 5.释放json对象 */
    json_object_put(jsonObj);

    /* 接收服务器的json信息 */
    /* 6.接收服务器信息 */
    string resInfo;
    client->recvMessage(resInfo);
    cout << resInfo << endl;

    /* 将字符串转为json对象 */
    json_object *resObj = json_tokener_parse(resInfo.c_str());

    int status = json_object_get_int(json_object_object_get(resObj, "status"));
    json_object_put(resObj);
    if (status == REGISTER_SUCCESS)
    {
        cout << " ===== 注册成功！ ===== " << endl;
        return true;
    }
    else
    {
        cout << "===== 注册失败！===== " << endl;
        return false;
    }
}

/* 登录函数 */
int loginInfo(StdTcpSocket *client)
{

    string username;
    cout << "请输入账号:";
    cin >> username;

    string password;
    cout << "请输入密码:";
    cin >> password;

    /* {} 叫做json对象 */
    /* 发送信息 */
    /* 1.创建json对象 */
    json_object *jsonObj = json_object_new_object();

    /* 2.向json对象添加<key,value>键值对 */
    json_object_object_add(jsonObj, "type", json_object_new_int(LOGIN));
    json_object_object_add(jsonObj, "name", json_object_new_string(username.c_str()));
    json_object_object_add(jsonObj, "passwd", json_object_new_string(password.c_str()));

    /* 3.将json对象转化为字符串 */
    const char *jsonStr = json_object_to_json_string(jsonObj);

    /* 4.发送到服务器 */
    client->sendMessage(jsonStr);

    /* 5.释放json对象 */
    json_object_put(jsonObj);

    /* 接收信息 */
    /* 6.接收服务器信息 */
    string resInfo;
    client->recvMessage(resInfo);

    /* 将字符串转为json对象 */
    json_object *resObj = json_tokener_parse(resInfo.c_str());

    int status = json_object_get_int(json_object_object_get(resObj, "status"));
    json_object_put(resObj);
    if (status == LOGIN_SUCCESS)
    {
        cout << " ===== 登录成功！ ===== " << endl;
        return true;
    }
    else if (status == LOGIN_NO_USER)
    {
        cout << " ===== 该用户不存在！ ===== " << endl;
        return false;
    }
    else
    {
        cout << " ===== 密码错误！ ===== " << endl;
        return false;
    }
}
void addFriendInfo(StdTcpSocket *client)
{
    string destName;
    cout << "请输入好友的姓名:";
    cin >> destName;

    /* 创建好友申请的json对象 */
    json_object *jsonObj = json_object_new_object();
    json_object_object_add(jsonObj, "type", json_object_new_int(FRIEND_REQUEST));
    json_object_object_add(jsonObj, "destName", json_object_new_string(destName.c_str()));

    /* 发送到服务器 */
    const char *jsonStr = json_object_to_json_string(jsonObj);
    client->sendMessage(jsonStr);

    json_object_put(jsonObj);

    /* 接收服务器申请是否发送成功信息 */
    // string resInfo;
    // client->recvMessage(resInfo);
    // cout << resInfo << endl;
}

/* 处理好友申请 */
void handleFriendRequest(StdTcpSocket *client)
{
    string msg;
    client->recvMessage(msg);
    cout << "msg " <<  msg << endl;
    json_object *jsonObj = json_tokener_parse(msg.c_str());
    int type = json_object_get_int(json_object_object_get(jsonObj, "type"));

    if (type == FRIEND_REQUEST)
    {
        string srcName = json_object_get_string(json_object_object_get(jsonObj, "srcName"));
        cout << "你收到来自 " << srcName << " 的好友申请！" << endl;
        cout << "是否同意？(1:同意，2:拒绝): ";

        /* 1.创建json对象 */
        json_object *resObj = json_object_new_object();
        /* 2.向json对象添加<key, value>键值对 */
        json_object_object_add(resObj, "type", json_object_new_int(FRIEND_RESULT));
        json_object_object_add(resObj, "srcName", json_object_new_string(srcName.c_str()));

        int choice = 0;
        cin >> choice;
        switch (choice)
        {
        case 1:
            cout << "您已同意好友申请" << endl;
            json_object_object_add(resObj, "status", json_object_new_int(FRIEND_ACCEPT));
            break;
        case 2:
            cout << "您已拒绝好友申请" << endl;
            json_object_object_add(resObj, "status", json_object_new_int(FRIEND_REJECT));
            break;
        default:
            break;
        }
        /* 给服务器反馈好友申请结果 */
        const char *resStr = json_object_to_json_string(resObj);
        cout << "反馈结果 " << resStr << endl;
        client->sendMessage(resStr);
        json_object_put(resObj); // 确保销毁 JSON 对象
    }
}

bool recvAddFriendResult(StdTcpSocket *client)
{
/* 接收是否成功加为好友信息 */
    string msg;
    client->recvMessage(msg);
    
    cout << msg << endl;

    json_object *recvJsonObj = json_tokener_parse(msg.c_str());
    int type = json_object_get_int(json_object_object_get(recvJsonObj, "type"));
    string destName = json_object_get_string(json_object_object_get(recvJsonObj, "destName"));
    int status = json_object_get_int(json_object_object_get(recvJsonObj, "status"));
    cout << "test1" << endl;
    if (type == FRIEND_RESULT)
    {
        json_object_put(recvJsonObj);
        if (status == FRIEND_ACCEPT)
        {
            cout << " 添加" << destName << "好友成功 " << endl;
            return true;
        }
        else if (status == FRIEND_REJECT)
        {
            cout << " 添加" << destName << "好友失败 " << endl;
            return false;
        }
    }
    return false;
}


/* 登录之后页面 */
void chatInterface(StdTcpSocket *client)
{
    sleep(1);
    system("clear");
    int choice = 0;
    cout << "欢迎进入聊天界面！" << endl;
    cout << "1.发送好友申请" << endl;
    cout << "2.处理好友消息" << endl;

    while (1)
    {
        cout << "请输入你的选择：";
        cin >> choice;

        switch (choice)
        {
        case 1:
            addFriendInfo(client);
            recvAddFriendResult(client);
            break;

        case 2:
            handleFriendRequest(client);
            break;

        default:
            cout << "无效选择，请重新输入。" << endl;
            break;
        }
    }
}

int main()
{
    StdTcpSocket client;

    client.connectToServer("192.168.152.128", 8888);

    if (client.isConnected() == false)
    {
        std::cout << "连接失败" << endl;
        exit(-1);
    }

    signUpLoginInterFace();

    int choice = 0;
    int ret = 0;
    while (1)
    {

        cout << "请输入你的选择：";
        cin >> choice;

        switch (choice)
        {
        case 1:
            ret = registerInfo(&client);
            if (ret == true)
            {
                /* 跳转到新界面 */
                cout << "账号注册成功，进入聊天界面..." << endl;
                chatInterface(&client);
            }
            continue;

        case 2:
            ret = loginInfo(&client);
            if (ret == true)
            {
                /* 跳转到新界面 */
                cout << "登录成功，进入聊天界面..." << endl;
                chatInterface(&client);
            }
            break;

        default:
            cout << "无效选择，请重新输入。" << endl;
            break;
        }
    }
}